import React, {Component} from 'react';
import {
  Table,
  Badge,
  Card,
  Input,
  Select,
  message,
  Modal,
  Tooltip,
  Button,
  Icon,
  Tree
} from 'antd';

import {connect} from "dva";
import SearchForm from '../../components/AutoForm/SearchForm';
import EditForm from '../../components/AutoForm/EditForm';

const {Option} = Select;
const {TextArea} = Input;
const confirm = Modal.confirm;
const { TreeNode } = Tree;


const statusMap = ['processing', 'warning'];
const status = ['使用中', '锁定'];

const searchFields = [
  {
    cols: [
      {
        md: 6,
        label: '名称',
        name: 'name',
        component: <Input placeholder="请输入"/>
      },
      {
        md: 6,
        label: '编码',
        name: 'code',
        component: <Input placeholder="请输入"/>
      },
      {
        md: 6,
        label: '使用状态',
        name: 'isLock',
        component: <Select placeholder="请选择" style={{width: '100%'}}>
          <Option value="0">使用中</Option>
          <Option value="1">锁定</Option>
        </Select>
      }
    ]
  }
];


@connect(({companyType, loading}) => ({
  tableLoading: loading.effects['companyType/page'],
  tableData: companyType.list,
  modalUpdateLoading: loading.effects['companyType/update'],
  modalInsertLoading: loading.effects['companyType/insert'],
  modalTreeLoading: loading.effects['companyType/compTypeResSave'],
  searchForm: companyType.searchForm,
  modalForm: companyType.modalForm,
  addForm: companyType.addForm,
  modalVisible: companyType.modalVisible,
  selection: companyType.selection,
  optFlag: companyType.optFlag,
  treeModalTitle: companyType.treeModalTitle,
  treeModalVisible: companyType.treeModalVisible,
  treeData: companyType.treeData,
  treeSelectKeys: companyType.treeSelectKeys,
  treeSubmitData: companyType.treeSubmitData,
  activeTypeId: companyType.activeTypeId,
  expandedKeys: companyType.expandedKeys,
  autoExpandParent: companyType.autoExpandParent
}))
export default class Type extends Component {


  columns = [
    {
      key: 1,
      title: '序号',
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: '编码',
      dataIndex: 'code',
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '描述',
      dataIndex: 'descr',
    },
    {
      title: '锁定/使用',
      dataIndex: 'isLock',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]}/>;
      },
    },
    {
      title: '操作',
      render: (text, record, index) => {
        return (
          <div>
            <Tooltip title="资源分配"><Button onClick={() => this.handleResourcesTree(text, record, index)}
                                          shape="circle" size="small"><Icon type="appstore"/></Button></Tooltip>
          </div>
        )
      },
    }
  ];

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'companyType/page',
    })
  }

  handleSearch = () => {
    const {dispatch, searchForm} = this.props;
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const param = {
      ...searchValue,
    };
    dispatch({
      type: 'companyType/page',
      payload: param
    })
  }

  handleSearchChange = (fields) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'companyType/handleSearchChange',
      payload: fields
    })
  }

  handleModalVisible = (opt) => {
    const {dispatch, modalVisible, selection, addForm} = this.props;
    let payload = {modalVisible: !modalVisible};
    let modalForm = {};
    if ('edit' === opt) {
      if (JSON.stringify(selection) === '{}') {
        message.error('请选择一条记录');
        return;
      } else {
        Object.keys(selection).map((key) => {
          modalForm[key] = {value: selection[key]}
        })
      }
    } else if ("add" === opt) {
      Object.keys(addForm).map((key) => {
        modalForm[key] = {value: addForm[key]}
      })
    }

    if (!modalVisible) {
      payload.optFlag = opt;
      payload.modalForm = modalForm;
    }
    dispatch({
      type: 'companyType/handleModalVisible',
      payload: payload
    })
  }

  handleOk = (fields) => {
    const {dispatch, optFlag, searchForm} = this.props;
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const payload = {
      fields: fields,
      searchForm: searchValue
    }
    if (optFlag === 'add') {
      dispatch({
        type: 'companyType/insert',
        payload: payload
      })
    } else if (optFlag === 'edit') {
      dispatch({
        type: 'companyType/update',
        payload: payload
      })
    }
  }

  handleDel = () => {
    const {dispatch, selection, searchForm} = this.props;
    if (JSON.stringify(selection) === '{}') {
      message.error('请选择一条记录');
      return;
    }
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const payload = {
      fields: selection,
      searchForm: searchValue
    }
    confirm({
      title: '是否确认删除此公司类型?',
      content: `编码：${selection.code}; 名称：${selection.name}`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'companyType/del',
          payload: payload,
        });
      },
    });
  }

  handleModalChange = (fields) => {
    const {dispatch, optFlag, addForm} = this.props;
    const payload = {fields: fields, optFlag: optFlag, addForm: addForm};
    dispatch({
      type: 'companyType/handleModalChange',
      payload: payload
    })
  }

  onSelect = (record) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'companyType/handleTableSelection',
      payload: record
    })
  };

  handleResourcesTree = (text, record, index) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'companyType/getTreeData',
      payload: {compTypeId: record.id}
    }).then(() => {
      this.handleTreeVisible();
    })
    dispatch({
      type: 'companyType/handleTreeTitleChange',
      payload: `分配资源(编码：${record.code}，名称：${record.name})`
    })
    dispatch({
      type: 'companyType/handleActiveTypeChange',
      payload: record.id
    })
  }

  handleTreeVisible = () => {
    const {dispatch,treeModalVisible} = this.props;
    dispatch({
      type: 'companyType/handleTreeVisible',
      payload: !treeModalVisible
    })
  }

  treeOnCheck = (checkedKeys,e) =>{
    const keys = checkedKeys.concat(e.halfCheckedKeys);
    const {dispatch} = this.props;
    dispatch({
      type: 'companyType/handleSelectKeys',
      payload: checkedKeys
    });
    dispatch({
      type: 'companyType/handleTreeSubmitData',
      payload: keys
    });
  }

  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} />;
    });

  handleTreeOk = () => {
    const { dispatch, activeTypeId, treeSubmitData } = this.props;
    if(!treeSubmitData.length){
      message.error('没有修改，无需提交');
      return;
    }
    dispatch({
      type: 'companyType/compTypeResSave',
      payload: {compTypeId: activeTypeId, resourceIds: treeSubmitData}
    })
  }
  onTreeExpand = expandedKeys => {
    console.log('onExpand', expandedKeys);
    const { dispatch } = this.props;
    dispatch({
      type: "companyType/treeExpand",
      payload: {expandedKeys: expandedKeys, autoExpandParent: false}
    })
  };
  render() {
    const {
      tableLoading,
      tableData,
      searchForm,
      modalForm,
      modalVisible,
      optFlag,
      modalUpdateLoading,
      modalInsertLoading,
      modalTreeLoading,
      treeModalTitle,
      treeModalVisible,
      treeData,
      treeSelectKeys,
      expandedKeys,
      autoExpandParent
    } = this.props;
    const rowSelection = {
      type: "radio",
      onSelect: this.onSelect
    }
    const EditRows = [
      {
        cols: [
          {
            label: '名称',
            name: 'name',
            md: 18,
            rules: [{required: true, message: '请输入至少四个字符！', min: 4}],
            component: <Input placeholder="请输入名称"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '编码',
            name: 'code',
            md: 18,
            rules: [{required: true, message: '请输入至少四个字符！', min: 4}],
            component: <Input disabled={optFlag === 'add' ? false : true} placeholder="请输入编码"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '描述',
            name: 'descr',
            md: 18,
            component: <TextArea placeholder="请输入描述"/>
          },
          {
            name: 'id',
            md: 0,
            component: <Input type={'hidden'}/>
          },
        ]
      },
    ]
    return (
      <Card bodyStyle={{padding: 0}}>
        <SearchForm
          header="公司类型->操作"
          layout="inline"
          fields={searchFields}
          fieldValue={searchForm}
          onSubmit={this.handleSearch}
          onModal={this.handleModalVisible}
          onFieldsChange={this.handleSearchChange}
          onDel={this.handleDel}
        />
        <Table
          columns={this.columns}
          loading={tableLoading}
          dataSource={tableData}
          rowSelection={rowSelection}
          rowKey={record => record.id}
          scroll={{x: 'max-content'}}
          size="small"
          bordered/>
        <EditForm
          rows={EditRows}
          fieldValue={modalForm}
          optFlag={optFlag}
          visible={modalVisible}
          confirmLoading={modalUpdateLoading || modalInsertLoading}
          onFieldsChange={this.handleModalChange}
          onOk={this.handleOk}
          onCancel={this.handleModalVisible}
        />

        <Modal
          visible={treeModalVisible}
          title={treeModalTitle}
          okText="确定"
          cancelText="取消"
          onCancel={this.handleTreeVisible}
          onOk={this.handleTreeOk}
          confirmLoading={modalTreeLoading}
          bodyStyle={{height: "600px", overflowY: "auto"}}
        >
            <Tree
              checkable
              showLine
              onExpand={this.onTreeExpand}
              checkedKeys={treeSelectKeys}
              onCheck={this.treeOnCheck}
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
            >
              {this.renderTreeNodes(treeData)}
            </Tree>


        </Modal>
      </Card>
    );
  }
}
